//
//  XGL_RequestConfigurationProtocol.swift
//  Maternal
//
//  Created by ios on 2021/6/16.
//

import Foundation
import PanKit
import Moya
import Alamofire
import SmartCodable

public typealias PanRequestManager = PanKit.PanRequestManager
public typealias PanTimer = PanKit.PanTimer

let productionUrl: String = "https://berrly.xyz"
enum RequestEnvironment {
    case test,production
    var baseUrl: String{
        var url = productionUrl
        #if DEBUG
        switch self {
        case .test:
            url = "https://test.lejun.co"
            break
        case .production:
            url = productionUrl
            break
        }
        #endif
        return url
    }
}

var requestBaseUrl: RequestEnvironment = .production

protocol XGL_RequestConfigurationProtocol {
    func requestConfiguration()
}

extension XGL_RequestConfigurationProtocol{
    func requestConfiguration(){
    
        let lock = PanLock()
        lock.lock()
        PanRequestConfig.share.successCode = "0x200"
        PanRequestConfig.share.baseUrl = requestBaseUrl.baseUrl
        PanRequestConfig.share.managerModel = .HTTPS
        PanRequestConfig.share.requestResult = "success"
        PanRequestConfig.share.responseReult = "data"
        PanRequestConfig.share.responseCode = "resCode"
        PanRequestConfig.share.responseMessage = "message"
        PanRequestConfig.share.plugins = [XGL_RequestPlugTool()]
        if let dic = RequestParameters().toDictionary() {
            PanRequestConfig.share.parameters = dic
        }
        let uetk = XGL_userDataCacheManager.shared.token.token
        if let index = PanRequestConfig.share.headers.firstIndex(where: {$0.name == "token"}){
            if PanRequestConfig.share.headers[index].value != uetk{
                PanRequestConfig.share.headers[index] = HTTPHeader(name: "token", value: uetk)
            }
        }else{
            if PanRequestConfig.share.headers.contains(where: {$0.name == "appId"}) == false{
                PanRequestConfig.share.headers = [HTTPHeader(name: "token", value: uetk),HTTPHeader(name: "appId", value: XGL_UdidTool.getUUIDString()),HTTPHeader(name: "version", value: AppversionCodeStr),HTTPHeader(name: "packageName", value: AppPackageName),HTTPHeader(name: "cardtype", value: "460"),HTTPHeader(name: "deviceType", value: DeviceType),HTTPHeader(name: "useVpn", value: "0"),HTTPHeader(name: "locale", value: currentLanguage),HTTPHeader(name: "timeOffset", value: currentTimeStamp)]
            }
        }
        lock.unlock()
    }
}


struct RequestParameters: SmartCodable{
    var token: String = XGL_userDataCacheManager.shared.token.token
    var packageName: String = AppPackageName
    var appId: String = XGL_UdidTool.getUUIDString()
    var deviceType: String = DeviceType
    var version: String = AppversionCodeStr
    var cardType: String = "460"
    var useVpn: String = "0"
    var locale: String = currentLanguage
    var timeOffset: String = currentTimeStamp
}
